package com.rmy.service.impl;

import com.rmy.device.onbon.*;
import com.rmy.domain.CompArea;
import com.rmy.domain.CompParam;
import com.rmy.service.CompInterface;
import onbon.bx06.Bx6GEnv;
import onbon.bx06.Bx6GScreenClient;
import onbon.bx06.Bx6GScreenProfile;
import onbon.bx06.area.TextCaptionBxArea;
import onbon.bx06.area.page.TextBxPage;
import onbon.bx06.file.ProgramBxFile;
import onbon.bx06.series.Bx6E;
import onbon.bx06.utils.DisplayStyleFactory;
import onbon.bx06.utils.TextBinary;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.List;

@Service("onbonBx06CompDevice")
public class OnbonBx06CompDevice implements CompInterface {

    private static final Logger logger = LoggerFactory.getLogger(OnbonBx06CompDevice.class);

    @Override
    public boolean sendComp(String strIp, int nPort, CompParam compParam, List<CompArea> compAreaList) throws Exception {
        List<BxArea> areas = new ArrayList<BxArea>();
        Bx6GEnv.initial(30000);
        Bx6GScreenClient screen = new Bx6GScreenClient("compScreen",new Bx6E());
        if (!screen.connect(strIp, nPort)) {
            throw new Exception("connect " + strIp + ":" + nPort + " failed!!!");
        }
        Bx6GScreenProfile profile = screen.getProfile();
        DisplayStyleFactory.DisplayStyle[] styles = DisplayStyleFactory.getStyles().toArray(new DisplayStyleFactory.DisplayStyle[0]);
        ProgramBxFile pf = new ProgramBxFile( "P000",screen.getProfile() );

        // 1. 循环取值
        for (CompArea compArea : compAreaList) {
            TextCaptionBxArea area = new TextCaptionBxArea(compArea.getX(),compArea.getY(),compArea.getW(),compArea.getH(), profile);
            TextBxPage page = new TextBxPage(compArea.getContent());
            page.setDisplayStyle(styles[compArea.getMode()]);
            page.setHorizontalAlignment(TextBinary.Alignment.CENTER);
            if (compArea.getSpeed() != null) {
                page.setSpeed(compArea.getSpeed());
            }
            if (compArea.getHoldtime() != null) {
                page.setStayTime(compArea.getHoldtime());
            }
            area.addPage(page);
            pf.addArea(area);
        }
        // 更新节目
        screen.writeProgram( pf );
        // 断开连接
        screen.disconnect();

        return true;
    }
}
